<template>
  <div class="task-home-container">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="container">
        <div class="header-content">
          <h1 class="app-title">任务管理</h1>
          <div class="header-buttons">
            <button @click="goToHistory" class="header-btn">
              <i class="fa fa-history"></i> 历史
            </button>
            <button @click="goToAddTask" class="header-btn header-btn-primary">
              <i class="fa fa-plus-circle"></i> 添加任务
            </button>
            <button @click="goToUserDetail" class="header-btn">
              <i class="fa fa-user"></i> 用户详情
            </button>
            <button @click="goToTaskDetail" class="header-btn">
              <i class="fa fa-tasks"></i> 任务详情
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="container">
      <!-- 筛选工具栏 -->
      <div class="filter-bar">
        <div class="filter-group">
          <label class="filter-label">优先级</label>
          <select v-model="filter.priority" class="filter-select">
            <option value="all">全部</option>
            <option value="高">高</option>
            <option value="中">中</option>
            <option value="低">低</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label class="filter-label">日期</label>
          <select v-model="filter.date" class="filter-select">
            <option value="all">全部</option>
            <option value="today">今天</option>
            <option value="week">本周</option>
            <option value="future">未来</option>
            <option value="overdue">已过期</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label class="filter-label">排序</label>
          <select v-model="sortBy" class="filter-select">
            <option value="dueDateAsc">截止日期 (早到晚)</option>
            <option value="dueDateDesc">截止日期 (晚到早)</option>
            <option value="priorityDesc">优先级 (高到低)</option>
            <option value="priorityAsc">优先级 (低到高)</option>
            <option value="createTime">创建时间</option>
          </select>
        </div>
      </div>

      <!-- 任务统计卡片 -->
      <div class="stats-card">
        <div class="stat-item">
          <div class="stat-value">{{ tasks.length || 0 }}</div>
          <div class="stat-label">总任务</div>
        </div>
        <div class="stat-item">
          <div class="stat-value text-success">{{ completedCount }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-value text-warning">{{ overdueCount }}</div>
          <div class="stat-label">已过期</div>
        </div>
        <div class="stat-item">
          <div class="stat-value text-primary">{{ todayCount }}</div>
          <div class="stat-label">今日任务</div>
        </div>
      </div>

      <!-- 任务列表 -->
      <div class="task-list">
        <!-- 空状态 -->
        <div v-if="filteredTasks.length === 0" class="empty-state">
          <div class="empty-icon">
            <i class="fa fa-tasks"></i>
          </div>
          <h3 class="empty-title">暂无任务</h3>
          <p class="empty-text">点击下方按钮创建你的第一个任务</p>
          <button @click="goToAddTask" class="empty-cta">
            <i class="fa fa-plus"></i> 创建任务
          </button>
        </div>
        
        <!-- 任务卡片 -->
        <div v-else class="task-cards">
          <div 
            v-for="task in filteredTasks" 
            :key="task.id" 
            class="task-card"
            :class="{ 'task-completed': task.completed }"
            @click="goToTaskDetail(task.id)"
          >
            <!-- 任务优先级标记 -->
            <div class="task-priority-badge" :class="getPriorityClass(task.priority)"></div>
            
            <!-- 任务内容 -->
            <div class="task-content">
              <div class="task-header">
                <h3 class="task-title">{{ task.title }}</h3>
                <div class="task-status" v-if="task.completed">
                  <i class="fa fa-check-circle text-success"></i> 已完成
                </div>
                <div class="task-status overdue" v-else-if="isOverdue(task)">
                  <i class="fa fa-exclamation-circle text-danger"></i> 已过期
                </div>
              </div>
              
              <p class="task-description">{{ task.description || '无描述' }}</p>
              
              <div class="task-meta">
                <span class="task-date">
                  <i class="fa fa-calendar-o"></i> 
                  {{ formatDate(task.dueDate) || '无截止日期' }}
                </span>
                
                <div class="task-tags">
                  <i class="fa fa-tags"></i>
                  <span v-for="tag in task.tags || []" :key="tag" class="tag">{{ tag }}</span>
                </div>
              </div>
            </div>
            
            <!-- 任务操作 -->
            <div class="task-actions">
              <button 
                class="complete-btn"
                @click.stop="toggleComplete(task.id)"
              >
                <i class="fa" :class="task.completed ? 'fa-check-square text-success' : 'fa-square-o'"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 浮动添加按钮 -->
    <button @click="goToAddTask" class="floating-add-btn">
      添加任务
    </button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const tasks = ref([])
const filter = ref({ priority: 'all', date: 'all' })
const sortBy = ref('dueDateAsc')

// 任务统计
const completedCount = computed(() => 
  (tasks.value || []).filter(t => t.completed).length
)

const overdueCount = computed(() => 
  (tasks.value || []).filter(t => 
    t.dueDate && new Date(t.dueDate) < new Date() && !t.completed
  ).length
)

const todayCount = computed(() => 
  (tasks.value || []).filter(t => {
    if (!t.dueDate) return false
    const dueDate = new Date(t.dueDate)
    const today = new Date()
    return dueDate.toDateString() === today.toDateString()
  }).length
)

// 加载任务
onMounted(() => {
  try {
    const storedTasks = localStorage.getItem('tasks')
    tasks.value = storedTasks ? JSON.parse(storedTasks) : []
  } catch (error) {
    console.error('Failed to load tasks from localStorage:', error)
    tasks.value = [] // 确保 tasks 始终为数组
  }
})

// 计算筛选后任务
const filteredTasks = computed(() => {
  let result = [...(tasks.value || [])]
  
  // 优先级筛选
  if (filter.value.priority !== 'all') {
    result = result.filter(task => task.priority === filter.value.priority)
  }
  
  // 日期筛选
  const today = new Date()
  result = result.filter(task => {
    const dueDate = task.dueDate ? new Date(task.dueDate) : null
    switch (filter.value.date) {
      case 'today': return dueDate && dueDate.toDateString() === today.toDateString()
      case 'week': return dueDate && isThisWeek(dueDate)
      case 'future': return !dueDate || dueDate > today
      case 'overdue': return dueDate && dueDate < today && !task.completed
      default: return true
    }
  })
  
  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'dueDateAsc': return dateSort(a.dueDate, b.dueDate, 'asc')
      case 'dueDateDesc': return dateSort(a.dueDate, b.dueDate, 'desc')
      case 'priorityDesc': return prioritySort(a, b, 'desc')
      case 'priorityAsc': return prioritySort(a, b, 'asc')
      default: return new Date(b.createdAt || 0) - new Date(a.createdAt || 0) // 创建时间倒序
    }
  })
  
  return result
})

// 日期排序辅助函数
const dateSort = (aDate, bDate, order) => {
  const dateA = aDate ? new Date(aDate) : new Date('9999-12-31')
  const dateB = bDate ? new Date(bDate) : new Date('9999-12-31')
  return order === 'asc' ? dateA - dateB : dateB - dateA
}

// 优先级排序辅助函数
const prioritySort = (a, b, order) => {
  const prioA = ['低', '中', '高'].indexOf(a.priority)
  const prioB = ['低', '中', '高'].indexOf(b.priority)
  return order === 'asc' ? prioA - prioB : prioB - prioA
}

// 检查本周
const isThisWeek = (date) => {
  const today = new Date()
  const dayOfWeek = today.getDay() || 7
  const start = new Date(today)
  start.setDate(today.getDate() - dayOfWeek + 1)
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  return date >= start && date <= end
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return null
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  return {
    'high-priority': priority === '高',
    'medium-priority': priority === '中',
    'low-priority': priority === '低'
  }
}

// 导航函数
const goToHistory = () => router.push('/history')
const goToAddTask = () => router.push('/add-task')
const goToUserDetail = () => router.push('/user-profile')
const goToTaskDetail = (id) => router.push(`/task-detail/${id}`)

// 切换完成状态
// TaskHome.vue 的 toggleComplete 函数
const toggleComplete = (id) => {
  const task = tasks.value.find(t => t.id === id)
  if (task) {
    task.completed = !task.completed
    // ✨ 记录完成时间
    if (task.completed) {
      task.completedAt = new Date().toISOString()
    } else {
      delete task.completedAt // 取消完成则移除时间
    }
    task.updatedAt = new Date().toISOString()
    localStorage.setItem('tasks', JSON.stringify(tasks.value))
  }
}

// 检查任务是否过期
const isOverdue = (task) => {
  return task.dueDate && new Date(task.dueDate) < new Date() && !task.completed
}
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary-color: #165DFF;
  --success-color: #36D399;
  --warning-color: #FFAA33;
  --danger-color: #F87272;
  --gray-50: #F9FAFB;
  --gray-100: #F3F4F6;
  --gray-200: #E5E7EB;
  --gray-300: #D1D5DB;
  --gray-400: #9CA3AF;
  --gray-500: #6B7280;
  --gray-600: #4B5563;
  --gray-700: #374151;
  --gray-800: #1F2937;
  --gray-900: #111827;
  
  --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  --card-hover-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

/* 全局样式 */
.task-home-container {
  min-height: 100vh;
  background-color: var(--gray-50);
  font-family: 'Inter', system-ui, sans-serif;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* 顶部导航栏 */
.app-header {
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 4rem;
}

.app-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--gray-800);
  margin: 0;
}

.header-buttons {
  display: flex;
  gap: 0.75rem;
}

.header-btn {
  background-color: var(--gray-700);
  color: #36D399;
  border: none;
  border-radius: 0.5rem;
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
}

.header-btn:hover {
  background-color: var(--gray-800);
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.header-btn:active {
  transform: translateY(0);
}

.header-btn i {
  margin-right: 0.5rem;
}

.header-btn-primary {
  background-color: var(--primary-color);
}

.header-btn-primary:hover {
  background-color: #0E42B3;
  box-shadow: 0 4px 6px -1px rgba(22, 93, 255, 0.2);
}

/* 筛选工具栏 */
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  background-color: white;
  padding: 1rem;
  border-radius: 0.75rem;
  box-shadow: var(--card-shadow);
  margin-bottom: 1.5rem;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-label {
  font-size: 0.9rem;
  color: var(--gray-600);
  font-weight: 500;
}

.filter-select {
  padding: 0.5rem 1rem;
  border: 1px solid var(--gray-200);
  border-radius: 0.5rem;
  font-size: 0.9rem;
  color: var(--gray-700);
  background-color: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-select:hover {
  border-color: var(--primary-color);
}

.filter-select:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
}

/* 统计卡片 */
.stats-card {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.stats-card .stat-item {
  background-color: white;
  border-radius: 0.75rem;
  padding: 1rem;
  box-shadow: var(--card-shadow);
  transition: all 0.2s ease;
}

.stats-card .stat-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--card-hover-shadow);
}

.stats-card .stat-value {
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--gray-800);
  margin-bottom: 0.25rem;
}

.stats-card .stat-label {
  font-size: 0.85rem;
  color: var(--gray-500);
}

.text-success { color: var(--success-color); }
.text-warning { color: var(--warning-color); }
.text-primary { color: var(--primary-color); }

/* 任务列表 */
.task-list {
  padding-bottom: 5rem; /* 为浮动按钮留出空间 */
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 0;
  text-align: center;
}

.empty-state .empty-icon {
  font-size: 4rem;
  color: var(--gray-300);
  margin-bottom: 1.5rem;
}

.empty-state .empty-title {
  font-size: 1.25rem;
  font-weight: 500;
  color: var(--gray-700);
  margin-bottom: 0.5rem;
}

.empty-state .empty-text {
  font-size: 0.9rem;
  color: var(--gray-500);
  margin-bottom: 1.5rem;
}

.empty-state .empty-cta {
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 1.5rem;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.empty-state .empty-cta:hover {
  background-color: #0E42B3;
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(22, 93, 255, 0.2);
}

.empty-state .empty-cta i {
  margin-right: 0.5rem;
}

/* 任务卡片 */
.task-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
}

.task-card {
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: var(--card-shadow);
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
  border: 1px solid var(--gray-100);
}

.task-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--card-hover-shadow);
}

.task-card .task-priority-badge {
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
}

.task-card .task-content {
  padding: 1.25rem;
}

.task-card .task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.task-card .task-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--gray-800);
  margin: 0;
}

.task-card .task-description {
  font-size: 0.9rem;
  color: var(--gray-600);
  line-height: 1.5;
  margin-bottom: 1rem;
  max-height: 3rem;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.task-card .task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  font-size: 0.85rem;
  color: var(--gray-500);
}

.task-card .task-meta i {
  margin-right: 0.3rem;
}

.task-card .task-status {
  font-size: 0.8rem;
  padding: 0.25rem 0.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
}

.task-card .task-status i {
  margin-right: 0.25rem;
}

.task-card .task-status.overdue {
  color: var(--danger-color);
  background-color: rgba(248, 114, 114, 0.1);
}

.task-card .task-actions {
  position: absolute;
  bottom: 1rem;
  right: 1rem;
}

.task-card .complete-btn {
  background: none;
  border: none;
  color: var(--gray-400);
  cursor: pointer;
  font-size: 1.2rem;
  transition: all 0.2s ease;
}

.task-card .complete-btn:hover {
  color: var(--success-color);
}

.task-card .tag {
  background-color: var(--gray-100);
  color: var(--gray-600);
  padding: 0.15rem 0.5rem;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  margin-right: 0.25rem;
}

/* 已完成任务样式 */
.task-completed {
  opacity: 0.7;
}

.task-completed .task-title {
  text-decoration: line-through;
  color: var(--gray-500);
}

/* 优先级样式 */
.high-priority { background-color: var(--danger-color); }
.medium-priority { background-color: var(--warning-color); }
.low-priority { background-color: var(--success-color); }

/* 浮动添加按钮 */
.floating-add-btn {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 3.5rem;
  height: 3.5rem;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 50%;
  font-size: 1.5rem;
  box-shadow: 0 10px 15px -3px rgba(22, 93, 255, 0.3);
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
}

.floating-add-btn:hover {
  background-color: #0E42B3;
  transform: scale(1.05);
  box-shadow: 0 10px 20px -3px rgba(22, 93, 255, 0.4);
}

.floating-add-btn:active {
  transform: scale(0.95);
}
</style>